import 'package:dio/dio.dart';
import '../models/music_model.dart';

class MusicApiService {
  static const String baseUrl = 'https://music.itzo.cn/a.php';
  late final Dio _dio;

  MusicApiService() {
    _dio = Dio(BaseOptions(
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Accept-Language': 'zh-CN,zh;q=0.9,en-GB;q=0.8,en-US;q=0.7,en;q=0.6',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Origin': 'https://music.itzo.cn',
        'Referer': 'https://music.itzo.cn/',
        'Sec-Ch-Ua': '"Google Chrome";v="141", "Not?A_Brand";v="8", "Chromium";v="141"',
        'Sec-Ch-Ua-Mobile': '?0',
        'Sec-Ch-Ua-Platform': '"Windows"',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'X-Requested-With': 'XMLHttpRequest',
      },
    ));
  }

  Future<Map<String, dynamic>> searchMusic(String keyword, {int page = 1, String type = 'netease'}) async {
    try {
      final formData = FormData.fromMap({
        'input': keyword,
        'filter': 'name',
        'type': type,
        'page': page.toString(),
      });

      final response = await _dio.post(
        baseUrl,
        data: formData,
        options: Options(
          headers: {
            'Referer': 'https://music.itzo.cn/a.php?name=${Uri.encodeComponent(keyword)}&type=$type',
          },
        ),
      );

      if (response.statusCode == 200) {
        final data = response.data;
        
        if (data is Map<String, dynamic>) {
          if (data['code'] == 200 && data['data'] != null) {
            final List<dynamic> musicList = data['data'];
            final List<MusicModel> results = musicList.map((item) => MusicModel.fromJson(item)).toList();
            
            return {
              'results': results,
              'hasMore': results.length >= 20, // 假设每页20条数据
              'currentPage': page,
              'error': null,
            };
          } else {
            return {
              'results': <MusicModel>[],
              'hasMore': false,
              'currentPage': page,
              'error': data['error'] ?? '搜索失败',
            };
          }
        }
      }
      
      return {
        'results': <MusicModel>[],
        'hasMore': false,
        'currentPage': page,
        'error': '请求失败',
      };
    } catch (e) {
      print('搜索音乐失败: $e');
      return {
        'results': <MusicModel>[],
        'hasMore': false,
        'currentPage': page,
        'error': '网络错误: $e',
      };
    }
  }


}